﻿package net.wangit.dev.settings;

import java.io.File;

import net.wangit.Path;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionResult;
import net.wangit.support.Action;
import net.wangit.util.FileUtil;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 创建域
 * 
 * @author watson
 * Feb 21, 2010
 */
public class CreateDomainAction implements Action {

	private static final Log log = LogFactory
			.getLog(net.wangit.dev.settings.CreateDomainAction.class);
	private static final String TEMPLATE = (new StringBuilder(String
			.valueOf(Path.getDomainPath("dev")))).append("/domain").toString();
	private static final String GLOBAL = (new StringBuilder(String.valueOf(Path
			.getHomePath()))).append("/global.xml").toString();

	public CreateDomainAction() {
	}

	public ActionContext execute(ActionContext ac) throws Exception {
		String domain = ac.getRequestParameter("domain.domain").toLowerCase();
		String target = (new StringBuilder(String.valueOf(Path
				.getDomainRootPath()))).append(domain).toString();
		File destDir = new File(target);
		if (destDir.exists()) {
			ActionResult ar = ac.getActionResult();
			ar.setSuccessful(false);
			ar.addError("创建域失败：指定域已存在！");
			return ac;
		}
		try {
			File srcDir = new File(TEMPLATE);
			FileUtil.copyDirectory(srcDir, destDir);
			FileUtil.rename((new StringBuilder(String.valueOf(target))).append(
					"/database/tempdomainname.properties").toString(),
					(new StringBuilder(String.valueOf(target))).append(
							"/database/").append(domain).append(".properties")
							.toString());
			FileUtil.rename((new StringBuilder(String.valueOf(target))).append(
					"/database/tempdomainname.script").toString(),
					(new StringBuilder(String.valueOf(target))).append(
							"/database/").append(domain).append(".script")
							.toString());
			String content = FileUtil.read((new StringBuilder(String
					.valueOf(target))).append("/datasource.xml").toString());
			content = StringUtil.replace(content, "tempdomainname", domain);
			FileUtil.saveTextFile(content, new File((new StringBuilder(String
					.valueOf(target))).append("/datasource.xml").toString()));
			content = FileUtil.read(GLOBAL);
			content = StringUtil.replace(content, "</domains>",
					(new StringBuilder("  <domain>")).append(domain).append(
							"</domain>\n  </domains>").toString());
			FileUtil.saveTextFile(content, new File(GLOBAL));
		} catch (Exception e) {
			ac.getActionResult().setSuccessful(false);
			log.error("create domain failed! ", e);
		}
		return ac;
	}

}
